import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ showSpinner: false })

const routes = [
  {
    path: '/'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/teacher',
    component: () => import('@/layouts/TeacherLayout.vue'),
    meta: { requiresAuth: true, role: 'teacher' },
    children: [
      {
        path: '',
        redirect: '/teacher/dashboard'
      },
      {
        path: 'dashboard',
        name: 'TeacherDashboard',
        component: () => import('@/views/teacher/Dashboard.vue')
      },
      {
        path: 'groups',
        name: 'TeacherGroupManagement',
        component: () => import('@/views/teacher/Groups.vue')
      },
      {
        path: 'questions',
        name: 'TeacherQuestionManagement',
        component: () => import('@/views/teacher/Questions.vue')
      },
      {
        path: 'papers',
        name: 'TeacherPaperManagement',
        component: () => import('@/views/teacher/Papers.vue')
      },
      {
        path: 'students',
        name: 'TeacherStudentManagement',
        component: () => import('@/views/teacher/Students.vue')
      },
      {
        path: 'grading',
        name: 'TeacherGradingManagement',
        component: () => import('@/views/teacher/Grading.vue')
      },
      {
        path: 'grading/detail/:submissionId?',
        name: 'TeacherGradingDetail',
        component: () => import('@/views/teacher/GradingDetail.vue')
      },
      {
        path: 'anticheat',
        name: 'TeacherAntiCheat',
        component: () => import('@/views/teacher/AntiCheat.vue')
      },
      {
        path: 'exam-composer',
        name: 'ExamComposer',
        component: () => import('@/views/teacher/ExamComposer.vue')
      }
    ]
  },
  {
    path: '/super-admin',
    component: () => import('@/layouts/SuperAdminLayout.vue'),
    meta: { requiresAuth: true, role: 'super_admin' },
    children: [
      {
        path: '',
        redirect: '/super-admin/dashboard'
      },
      {
        path: 'dashboard',
        name: 'SuperAdminDashboard',
        component: () => import('@/views/super-admin/Dashboard.vue')
      },
      {
        path: 'system',
        name: 'SystemManagement',
        component: () => import('@/views/super-admin/SystemManagement.vue')
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/super-admin/UserManagement.vue')
      },
      {
        path: 'logs',
        name: 'OperationLogs',
        component: () => import('@/views/super-admin/OperationLogs.vue')
      }
    ]
  },
  {
    path: '/student',
    component: () => import('@/layouts/StudentLayout.vue'),
    meta: { requiresAuth: true, role: 'student' },
    children: [
      {
        path: '',
        redirect: '/student/dashboard'
      },
      {
        path: 'dashboard',
        name: 'StudentDashboard',
        component: () => import('@/views/student/Dashboard.vue')
      },
      {
        path: 'exams',
        name: 'StudentExams',
        component: () => import('@/views/student/Exams.vue')
      },
      {
        path: 'exam/:id?',
        name: 'StudentExam',
        component: () => import('@/views/student/Exam.vue')
      },
      {
        path: 'profile',
        name: 'StudentProfile',
        component: () => import('@/views/student/Profile.vue')
      },
      {
        path: 'records',
        name: 'StudentRecords',
        component: () => import('@/views/student/Records.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  
  // console.log('路由守卫检查:', {
  //   to: to.path,
  //   requiresAuth: to.meta.requiresAuth,
  //   requiredRole: to.meta.role,
  //   isAuthenticated: userStore.isAuthenticated,
  //   userRole: userStore.userInfo?.role,
  //   userInfo: userStore.userInfo
  // })
  
  // 不需要认证的页面
  if (to.meta.requiresAuth === false) {
    next()
    return
  }
  
  // 检查用户是否已登录
  if (!userStore.isAuthenticated) {
    console.log('用户未登录，重定向到登录页')
    next('/login')
    return
  }
  
  // 如果用户已登录但没有用户信息，尝试初始化
  if (!userStore.userInfo) {
    console.log('用户已登录但缺少用户信息，尝试初始化')
    try {
      await userStore.initUser()
    } catch (error) {
      console.log('初始化用户信息失败，重定向到登录页')
      next('/login')
      return
    }
  }
  
  // 检查角色权限
  if (to.meta.role && to.meta.role !== userStore.userInfo?.role) {
    console.log('用户角色不匹配，重定向到对应页面', {
      required: to.meta.role,
      actual: userStore.userInfo?.role
    })
    // 根据用户角色重定向到对应的首页
    switch (userStore.userInfo?.role) {
      case 'super_admin':
        next('/super-admin/dashboard')
        break
      case 'teacher':
        next('/teacher/dashboard')
        break
      case 'student':
        next('/student/dashboard')
        break
      default:
        console.log('未知角色，重定向到登录页')
        next('/login')
    }
    return
  }
  
  // 根目录重定向
  if (to.path === '/') {
    switch (userStore.userInfo?.role) {
      case 'super-admin':
        next('/super-admin/dashboard')
        break
      case 'teacher':
        next('/teacher/dashboard')
        break
      case 'student':
        next('/student/dashboard')
        break
      default:
        next('/login')
    }
    return
  }
  
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router